<?php

namespace Repositories;

use Doctrine\ORM\EntityRepository;
use DoctrineExtensions\Paginate\Paginate as Paginate;

class CommonRepository extends EntityRepository
{
    protected $_entityClassName;
    protected $_recordCount;
    protected $_pageCount;

    public function getAll()
    {
        $q = $this->_em->createQuery("SELECT e FROM $this->_entityClassName e");
        $q->setMaxResults(100);
        return $q->getResult();
    }

    public function getPage($page_num = 0, $per_page = 10)
    {
        $limit = $per_page;
        $offset = $per_page * $page_num;

        $q = $this->_em->createQuery("SELECT e FROM $this->_entityClassName e");
        $q->setMaxResults($limit);
        $q->setFirstResult($offset);
        return $q->getResult();
    }

    public function getPageCount($size)
    {
        if ($this->_pageCount == null) {
            $this->_pageCount = ceil($this->getCount() / $size);
        }
        return $this->_pageCount;
    }

    public function getCount()
    {
        if ($this->_recordCount == null) {
            $q = $this->_em->createQuery("SELECT COUNT(e.id) FROM $this->_entityClassName e");
            $this->_recordCount = $q->getSingleScalarResult();
        }
        return $this->_recordCount;
    }    
    
    public function getListSort($page_num = 0, $per_page = 10)
    {
    	$limit = $per_page;
    	$offset = $per_page * $page_num;
    
    	$q = $this->_em->createQuery("SELECT e FROM $this->_entityClassName e");
    	$q->setMaxResults($limit);
    	$q->setFirstResult($offset);
    	return $q->getResult();
    }
    
    public function deleteById($id)
    {
    	$obj = $this->findOneById($id);
    	$this->_em->remove($obj);
    	$this->_em->flush();
    }
    
    public function paginatorCount()
    {
    	$query = $this->_em->createQuery("SELECT e FROM $this->_entityClassName e");
    	$count = Paginate::getTotalQueryResults($query);
    	return $count;
    }
    
    /*********** FUNCTION TO SEARCH ALL FORM   ************/
   	public function searchAllForm($name,$field,$key,$offset,$limitPerPage)
   	{
   	    $this->_entityClassName = 'Entities\Hae'.ucwords($name);
   		if ($key == 'sort')
   		{
   		    $query = $this->_em->createQuery("SELECT e FROM $this->_entityClassName e ORDER BY e.".$field." DESC");
   		}
   		else
   		{
   		    $query = $this->_em->createQuery("SELECT e FROM $this->_entityClassName e WHERE e.".$field." LIKE '%".$key."%' ");
   		}
   		
   		$paginateQuery = Paginate::getPaginateQuery($query, $offset, $limitPerPage);
   		$result = $paginateQuery->getResult();
   		return $result;
   	}
   	
    /*********** SAVE ALL  ************/
    public function saveAll($id=0,$name,$postArray)
    {
        $obj = (object) $postArray;
        if (isset($postArray['metatagEn']))
           $seo = $this->saveSeo($id,$postArray);
        $repository = '\Entities\Hae'.$name;
        $this->_repo = $this->_em->getRepository($repository);
        if ($id==0)
        {
        	$obj = new $repository;
        }
        else
        {
        	$obj = $this->_repo->findOneById($id);
        }
	    foreach($postArray as $key=>$value)
	    {
	        if ( $key !='image' && $key !='metatagVi' && $key !='metatagEn' && $key !='metatagJa' && $key !='metatagZh' && $key !='metatagFr' && $key !='keywordVi' && $key !='keywordEn' && $key !='keywordJa' && $key !='keywordZh' && $key !='keywordFr')
	        {	$set = 'set'.ucfirst($key);
	      		$obj->$set($value);
	        }
	    }
	    if (isset($postArray['metatagEn']))
	    {
	        $obj->setSeo($seo);	        
	    }
	   
	    $this->_em->persist($obj);
	    $this->_em->flush();
	   
	    die;
	    
    }
    /*********** SAVE SEO  ************/
    public function saveSeo($id = 0,$postArray)
    {
        $obj = (object) $postArray;
        
        $this->_repo = $this->_em->getRepository('Entities\HaeSeo');
        if ($id==0)
        {
        	$seo = new \Entities\HaeSeo;
        }
        else
        {
        	$seo = $this->_repo->findOneById($id);
        }
        
        // Set Alias For Seo
        $seo->setAliasVi($this->rewrite($obj->titleVi));
        $seo->setAliasEn($this->rewrite($obj->titleEn));
        $seo->setAliasJa($this->rewrite($obj->titleJa));
        $seo->setAliasZh($this->rewrite($obj->titleZh));
        $seo->setAliasFr($this->rewrite($obj->titleFr));
        // Set Metatag for Seo
        $seo->setMetatagVi($obj->metatagVi);
        $seo->setMetatagEn($obj->metatagEn);
        $seo->setMetatagJa($obj->metatagJa);
        $seo->setMetatagZh($obj->metatagZh);
        $seo->setMetatagFr($obj->metatagFr);
        //Set keyword for Seo
        $seo->setKeywordVi($obj->keywordVi);
        $seo->setKeywordEn($obj->keywordEn);
        $seo->setKeywordJa($obj->keywordJa);
        $seo->setKeywordZh($obj->keywordZh);
        $seo->setKeywordFr($obj->keywordFr);
         
        $this->_em->persist($seo);
	    $this->_em->flush();
	   
        
        return $seo;
    }
    
    function rewrite($string=null)
    {
    	// return if empty
    	if(empty($string)) return false;
    
    	// replace spaces by "-"
    	// convert accents to html entities
    	$string=htmlentities(utf8_decode(str_replace(' ', '-', $string)));
    
    	// remove the accent from the letter
    	$string=preg_replace(array('@&([a-zA-Z]){1,2}(acute|grave|circ|tilde|uml|ring|elig|zlig|slash|cedil|strok|lig){1};@', '@&[euro]{1};@'), array('${1}', 'E'), $string);
    
    	// now, everything but alphanumeric and -_ can be removed
    	// aso remove double dashes
    	$string=preg_replace(array('@[^a-zA-Z0-9\-_]@', '@[\-]{2,}@'), array('', '-'), html_entity_decode($string));
    	 
    	// Lowercase everything
    	$string= strtolower($string);
    	 
    	return $string;
    }

}